package com.gujiangbo.threadpool;

import java.util.concurrent.TimeUnit;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/3/11 16:17
 * @Version: 1.0
 * @Description: 自定义死锁
 */
public class DeadLockDemo {

    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldThread(lockA, lockB), "ThreadAAAA").start();
        new Thread(new HoldThread(lockB, lockA), "ThreadBBBB").start();
    }
}


class HoldThread implements Runnable {

    private String lockA;

    private String lockB;

    public HoldThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {

        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "持有锁" + lockA + "，尝试持有锁" + lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "持有锁" + lockB + ",尝试持有锁" + lockA);
            }
        }

    }
}